<?php

namespace app\home\controller;
use thirdapi\tp_wechat\WechatApi;

/**
 * 前台通用控制器
 * 主要获取首页聚合数据
 */
class CommonController extends WechatApi {

    public function _initialize()
    { 
        
    }
    
    public function login(){
        if(cookie('openid')){
            $user = db('user')->where(array('openid'=>cookie('openid')))->find();
            if(!$user){
                header("Location:https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->wx_config['appid']."&redirect_uri=".urlencode('http://'.$_SERVER['HTTP_HOST'].Url('Home/Oauth'))."&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
            }else{
                session('user_id',$user['id']);
                session('openid',cookie('openid'));
                header('Location:'.Url('Index/index'));
            }
        }else{
            header("Location:https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->wx_config['appid']."&redirect_uri=".urlencode('http://'.$_SERVER['HTTP_HOST'].Url('Home/Oauth'))."&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
        }
    }
    public function Oauth(){
        $code = $_GET['code'];
        $json = curl_request("https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->wx_config['appid']."&secret=".$this->wx_config['appsecret']."&code=".$code."&grant_type=authorization_code");
        $obj = json_decode($json);
        $user_access_token = $obj->access_token;
        $user_openid = $obj->openid;

        $json = curl_request("https://api.weixin.qq.com/sns/userinfo?access_token=".$user_access_token."&openid=".$user_openid."&lang=zh_CN ");
        $obj = json_decode($json);

        $data = array(
            'nickname' => $obj->nickname,
            'head_pic' => $obj->headimgurl
        );
        if(db('user')->where(array('openid'=>$user_openid))->find()){
            db('user')->where(array('openid'=>$user_openid))->update($data);
        }else{
            $data['openid'] = $obj->openid;
            $data['sm_time'] = time();
            $id = db('user')->insert($data);
            $reg_give = db('System')->where(['id'=>1])->value('reg_give');
            db('UserCoupon')->insert(['user_id'=>$id,'goods_id'=>$reg_give,'status'=>1]);
        }
        cookie('openid',$user_openid,3600*24*10);
        $this->redirect('Index/index');
    }
}